package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.ObjectUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description WeChatServiceImpl
 * @Author liangDong
 * @Date 2025-05-15  20:08
 */
@Service
public class WeChatServiceImpl implements WeChatService {

    private static final String REQUEST_URL ="https://api.weixin.qq.com/sns/jscode2session";

    private static final String PHONE_REQUEST_URL ="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private static final String TOKEN_URL ="https://api.weixin.qq.com/cgi-bin/token";

    @Value("${zzyl.wechat.appId}")
    private String appId;
    @Value("${zzyl.wechat.appSecret}")
    private String secretKey;
    //获取openid
    @Override
    public String getOpenId(String code) {
        Map<String, Object> requestUrlParam = getAppConfig();
        requestUrlParam.put("js_code",code);
        requestUrlParam.put("grant_type","authorization_code");
        String result = HttpUtil.get(REQUEST_URL,requestUrlParam);

        JSONObject jsonObject = JSONUtil.parseObj(result);
        //若code不正确，则获取不到openid，响应失败
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        return jsonObject.getStr("openid");
    }

    private Map<String, Object> getAppConfig() {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("appid",appId);
        requestParam.put("secret",secretKey);
        return requestParam;
    }

    //获取微信端的access_token
    private String getToken(){
        Map<String,Object> requestUrlParam = getAppConfig();
        requestUrlParam.put("grant_type","client_credential");
        String result = HttpUtil.get(TOKEN_URL,requestUrlParam);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjectUtil.isEmpty(jsonObject)) throw new RuntimeException("token为空");

        return jsonObject.getStr("access_token");
    }

    //获取手机号
    @Override
    public String getPhone(String phoneCode) {
        HashMap<String, Object> requestParam = new HashMap<>();
        //requestParam.put("access_token",getToken());
        requestParam.put("code",phoneCode);
        String url = PHONE_REQUEST_URL+getToken();
        String result = HttpUtil.post(url,JSONUtil.toJsonStr(requestParam));
        JSONObject jsonObject = JSONUtil.parseObj(result);

        //如果errcode不为0 就抛异常
        if (jsonObject.getInt("errcode") != 0) throw new RuntimeException(jsonObject.getStr("errmsg"));

        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }
}
